var util = require('../../utils/util.js');
var api = require('../../config/api.js');

var app = getApp();

Page({
  data: {
    cartGoods: [],
    cartTotal: {
      "goodsCount": 0,
      "goodsAmount": 0.00,
      "checkedGoodsCount": 0,
      "checkedGoodsAmount": 0.00
    },
    isEditCart: false,
    checkedAllStatus: false,
    editCartList: [],
    delGoods:[]
  },
  onLoad: function (options) {
    var that = this;
    // 页面初始化 options为页面跳转所带来的参数
    if (util.session == undefined){
      wx.showModal({
        title: '失败',
        content: '请先登录',
        success: function (res) {
          if (res.confirm) {
            wx.switchTab({
              url: '/pages/ucenter/index/index',
            });
          } else if (res.cancel) {

          }
        }
      })
    }else{
      util.request(api.getShopCart, { openId: util.session }, "GET")
        .then(function (res) {
          that.setData({
            cartGoods: res
          })
          let list = that.data.cartGoods;
          for (let i = 0; i < list.length; i++) {
            let price = parseInt(list[i].goodsNum);
            let temp = 'cartGoods[' + i + '].goodsNum';
            that.setData({
              [temp]: price
            })
          }
        })
    }
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    if (util.session == undefined) {

    } else {
      this.getCartList();
    }
   
  },
  onHide: function () {
    // 页面隐藏
    this.setData({
      checkedAllStatus: false,
      'cartTotal.checkedGoodsCount': 0,
      'cartTotal.checkedGoodsAmount':0
    })
  },
  onUnload: function () {
    // 页面关闭

  },
  getCartList: function () {
    let that = this;
    util.request(api.getShopCart, { openId: util.session }, "GET")
      .then(function (res) {
        that.setData({
          cartGoods: res
        })
        let list = that.data.cartGoods;
        for (let i = 0; i < list.length; i++) {
          let price = parseInt(list[i].goodsNum);
          let temp = 'cartGoods[' + i + '].goodsNum';
          that.setData({
            [temp]: price
          })
        }
      })
  },
  isCheckedAll: function () {
    //判断购物车商品已全选
    return this.data.cartGoods.every(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });
  },
  checkedItem: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let that = this;

    if (!this.data.isEditCart) {
      // util.request(api.CartChecked, { productIds: that.data.cartGoods[itemIndex].product_id, isChecked: that.data.cartGoods[itemIndex].checked ? 0 : 1 }, 'POST').then(function (res) {
      //   if (res.errno === 0) {
      //     console.log(res.data);
      //     that.setData({
      //       cartGoods: res.data.cartList,
      //       cartTotal: res.data.cartTotal
      //     });
      //   }

      //   that.setData({
      //     checkedAllStatus: that.isCheckedAll()
      //   });
      // });
    } else {
      //编辑状态
      let tmpCartData = this.data.cartGoods.map(function (element, index, array) {
        if (index == itemIndex){
          element.checked = !element.checked;
          if (element.checked == true){
            that.data.delGoods.push(that.data.cartGoods[itemIndex].goodsId);
          }else{
            for (let i = 0; i < that.data.delGoods.length;i++){
              if (that.data.delGoods[i] == that.data.cartGoods[itemIndex].goodsId){
                that.data.delGoods.splice(i,1);
              }
            }
          }
        }
        return element;
      });
     
      // console.log(that.data.cartGoods[itemIndex].goodsId);
      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount()
        // 'cartTotal.checkedGoodsAmount': that.getcheckedGoodsAmount()
      });
    }
  },
  getCheckedGoodsCount: function(){
    let checkedGoodsCount = 0;
    this.data.cartGoods.forEach(function (v) {
      if (v.checked === true) {
        checkedGoodsCount += v.goodsNum;
      }
    });
    return checkedGoodsCount;
  },
  getcheckedGoodsAmount:function(){
    let checkedGoodsAmount = 0;
    this.data.cartGoods.forEach(function (v) {
      if (v.checked === true) {
        checkedGoodsAmount += v.goodsNum * v.retailPrice;
      }
    });
    return checkedGoodsAmount;
  },
  checkedAll: function () {
    let that = this;
      //编辑状态
      let checkedAllStatus = that.isCheckedAll();
      let tmpCartData = this.data.cartGoods.map(function (v) {
        v.checked = !checkedAllStatus;
        return v;
      });

      that.setData({
        cartGoods: tmpCartData,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount(),
        'cartTotal.checkedGoodsAmount': that.getcheckedGoodsAmount()
      });
    

  },
  editCart: function () {
    var that = this;
    if (this.data.isEditCart) {
      this.setData({
        isEditCart: !this.data.isEditCart,
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount(),
        'cartTotal.checkedGoodsAmount': that.getcheckedGoodsAmount()
      });
    } else {
      //编辑状态
      let tmpCartList = this.data.cartGoods.map(function (v) {
        v.checked = false;
        return v;
      });
      this.setData({
        editCartList: this.data.cartGoods,
        cartGoods: tmpCartList,
        isEditCart: !this.data.isEditCart,
        checkedAllStatus: that.isCheckedAll(),
        'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount(),
        'cartTotal.checkedGoodsAmount': that.getcheckedGoodsAmount()
      });
      
    }

  },
  updateCart: function (goodsId, number, Price) {
    let that = this;
    let checkedGoodsAmount = 0;
    this.data.cartGoods.forEach(function (v) {
      if (v.goodsId === goodsId) {
        v.goodsNum = number;
      }
    });
    that.setData({
      'cartTotal.checkedGoodsCount': that.getCheckedGoodsCount(),
      'cartTotal.checkedGoodsAmount': that.getcheckedGoodsAmount()
    })
    // util.request(api.CartUpdate, {
    //   productId: productId,
    //   goodsId: goodsId,
    //   number: number,
    //   id: id
    // }, 'POST').then(function (res) {
    //   if (res.errno === 0) {
    //     console.log(res.data);
    //     that.setData({
    //       //cartGoods: res.data.cartList,
    //       //cartTotal: res.data.cartTotal
    //     });
    //   }

    //   that.setData({
    //     checkedAllStatus: that.isCheckedAll()
    //   });
    // });

  },
  cutNumber: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = (cartItem.goodsNum - 1 > 1) ? cartItem.goodsNum - 1 : 1;
    cartItem.goodsNum = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.goodsId, number, cartItem.retailPrice);
  },
  addNumber: function (event) {
    let itemIndex = event.target.dataset.itemIndex;
    let cartItem = this.data.cartGoods[itemIndex];
    let number = cartItem.goodsNum + 1;
    cartItem.goodsNum = number;
    this.setData({
      cartGoods: this.data.cartGoods
    });
    this.updateCart(cartItem.goodsId, number, cartItem.retailPrice);

  },
  checkoutOrder: function () {
    //获取已选择的商品
    let that = this;

    var checkedGoods = this.data.cartGoods.filter(function (element, index, array) {
      if (element.checked == true) {
        return true;
      } else {
        return false;
      }
    });

    if (checkedGoods.length <= 0) {
      return false;
    }
   
    wx.navigateTo({
      url: '../shopping/checkout/checkout?count=' + this.data.cartTotal.checkedGoodsCount + '&sum=' + this.data.cartTotal.checkedGoodsAmount + '&goods=' + JSON.stringify(checkedGoods) +'&freight='+10
    })
  },
  deleteCart: function () {
    //获取已选择的商品
    let that = this;
    let body={
      goodsId: that.data.delGoods.toString(),
      openId: util.session
    }
    util.request(api.delShopCart,body,'GET').then(function(res){
      util.request(api.getShopCart, { openId: util.session }, "GET")
        .then(function (res) {
          
          that.setData({
            cartGoods: res
          })
          let list = that.data.cartGoods;
          for (let i = 0; i < list.length; i++) {
            let price = parseInt(list[i].goodsNum);
            let temp = 'cartGoods[' + i + '].goodsNum';
            that.setData({
              [temp]: price
            })
          }
        })
    })
    // util.request(api.CartDelete, {
    //   productIds: productIds.join(',')
    // }, 'POST').then(function (res) {
    //   if (res.errno === 0) {
    //     console.log(res.data);
    //     let cartList = res.data.cartList.map(v => {
    //       console.log(v);
    //       v.checked = false;
    //       return v;
    //     });

    //     that.setData({
    //       cartGoods: cartList,
    //       cartTotal: res.data.cartTotal
    //     });
    //   }

    //   that.setData({
    //     checkedAllStatus: that.isCheckedAll()
    //   });
    // });
  }
})